package com.dc.kylin.logbackdesensitization.config;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.dc.kylin.logbackdesensitization.utils.DesensitizationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class DesensitizationPatternLayout extends PatternLayout {

    private static DesensitizationProperties properties;
    private static final AtomicBoolean initialized = new AtomicBoolean(false);

    @Autowired
    public void setProperties(DesensitizationProperties properties) {
        if (initialized.compareAndSet(false, true)) {
            DesensitizationPatternLayout.properties = properties;
            log.info("Desensitization pattern layout initialized");
            // 初始化脱敏工具
            log.info("Desensitization pattern layout properties: {}", properties);
            DesensitizationUtils.init(properties);
        }
    }

    @Override
    public String doLayout(ILoggingEvent event) {
        log.info("doLayout: {}", event);
        String originalLog = super.doLayout(event);
        return DesensitizationUtils.desensitize(originalLog);
    }
}
